/* CPROG14.CPP - Creating storage space on the fly with the keyword 'new' */
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
int main(void)
{
struct msgbox { int x, y; // Structure tag msgbox now defines the template for this type of structure
char text[100];
} *fred; /* *fred is just a pointer, not a
structure. Before we can do anything
through fred it must be initialised
with the address of a msgbox
structure. None yet exist. */
fred=new msgbox; /* Hopefully, new has found enough
free memory for a new msgbox type
structure, the address of which
goes into fred. */
if( fred == NULL ) // Just in case we're tight on RAM...
{
cputs("No room for a new test structure");
exit(0); // 0 goes into ERRORLEVEL to indicate failure
}
printf("%d\n", sizeof(*fred) );
/* Sizeof is a C++ keyword. It tells
you the size of the object named in
brackets. You can use variable names
or data types, such as sizeof(int).
With two integers and 100 bytes in a
char array, you'd expect the result
to be 104. */
// Let's initialise the new structure
fred->x=30; // the -> (points to) operator is used when fred is a pointer name instead of a structure name. The expected *fred.x means something different
fred->y=40;
strcpy(fred->text, "Greetings from the structure pointed to by fred!\n");